/**
 * Created by Flower付成华 on 2018/5/15.
 */

var loading_img_url = [];
var rootpath = "";//所有文件依赖的根路径，通过客户端传递过来
var playstate = 0;//默认的播放类型， 0：单句，1：本课  2：复读 3：连续 4：查词  
var audioHandler ;
var strs = [];
var curpindex = 0;
var curpagenum = 0;
var curobject;
var ispause = 0;//是否暂停
var curtime;//当前的 settimeout
var istranslation = false;

var curtrans = "";//当前选中的解释



var cur_volume = 50;//当前音量是多少
var isshowvolume = false;//是否显示开启音量
var isshowchecked = false;//是否显示可点击选读框
var isreadingover = false;//判断是否已经读取完了




var page_divs = new Array();//所有页面的div对象几个，二维数组
var divs = new Array();//一个页面的div 集合对象


//录音相关
var isfollow = false;//当前是否开启了跟读模式
var record_playnum = 1;//用来判断当前课本是第几次播放，来控制播放本地录音

//key都为小写字母
var dicdata = {};

var fudu_content = new Array();//要复读的内容 
var start_du_page;//开始从几页开始复读
var end_du_page;//结束从几页开始复读
var isfuduing = false;//判断是否正在复读
var pageindex = 0;
var nextpageindex_add = 1;//下页面的index 叠加量

var cur_play_sudu = 1;//当前播放的音频速率

var position_data ;//元数据


//newpage_page特有的
var date_start;
var date_end;
date_start = getNowFormatDate();

//菜单的选择事件
function rightmenu_click(onthis){
    var topage = $$(onthis).attr("curpage");
    dismissRightMenu();
    toPage(Number(topage)-1);
}


//跳转的页面
function toPage(topa){
    $(".flipbook").turn("page",Number(topa));
}

//跳转下一页
function toNextPage(){
 $(".flipbook").turn("next");   
}

//跳转下一页
function toPrevPage(){
 $(".flipbook").turn("previous");   
}


function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "";
    var seperator2 = "";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
        + "" + date.getHours() + seperator2 + date.getMinutes()
        + seperator2 + date.getSeconds();
    return currentdate;
}


//判断手机类型
window.onload = function () {

    var u = navigator.userAgent;
    if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {//安卓手机
    } else if (u.indexOf('iPhone') > -1) {//苹果手机
        //屏蔽ios下上下弹性
        $(window).on('scroll.elasticity', function (e) {
            e.preventDefault();
        }).on('touchmove.elasticity', function (e) {
            e.preventDefault();
        });
    } else if (u.indexOf('Windows Phone') > -1) {//winphone手机
    }



    


    //初始化audio
    initAudio();

    //执行默认
    ispause = 1;
    audioHandler.pause();
    $("#bottom_menu_img2").attr("src","../img/icon_play.png");

    clearBorder();

    // $("#div_container div").css('border','0px solid white');

   //获取本地的词典数据
   getDicts();
   
}






//加载页面
function loading() {
    var numbers = 0;
    var length = loading_img_url.length;

    for (var i = 0; i < length; i++) {
        var img = new Image();
        img.src = loading_img_url[i];
        img.onerror = function () {
            numbers += (1 / length) * 100;
        }
        img.onload = function () {
            numbers += (1 / length) * 100;
            $('.number').html(parseInt(numbers) + "%");
            console.log(numbers);
            if (Math.round(numbers) == 100) {
                //$('.number').hide();
                date_end = getNowFormatDate();
                var loading_time = date_end - date_start;
                //预加载图片
                $(function progressbar() {
                    //拼接图片
                    $('.shade').hide();
                    var tagHtml = "";
                    for (var i = 1; i <= length; i++) {
                        if (i == 1) {
                            tagHtml += ' <div id="first" style="background:url('+loading_img_url[i]+') center top no-repeat;background-size:100%"></div>';
                        } else if (i == length) {
                            tagHtml += ' <div id="end" style="background:url('+loading_img_url[i]+') center top no-repeat;background-size:100%"></div>';
                        } else {
                            tagHtml += ' <div style="background:url('+loading_img_url[i]+') center top no-repeat;background-size:100%"></div>';
                        }
                    }
                    $(".flipbook").append(tagHtml);
                    var w = $(".graph").width();
                    $(".flipbook-viewport").show();
                });
                //配置turn.js
                function loadApp() {
                    var w = $(window).width();
                    var h = $(window).height();
                    $('.flipboox').width(w).height(h);
                    $(window).resize(function () {
                        w = $(window).width();
                        h = $(window).height();
                        $('.flipboox').width(w).height(h);
                    });
                    $('.flipbook').turn({
                        // Width
                        width: w,
                        // Height
                        height: h,
                        // Elevation
                        elevation: 50,
                        display: 'single',
                        duration: '400',
                        // Enable gradients
                        gradients: true,
                        // Auto center this flipbook
                        autoCenter: true,
                        acceleration: true,
                        when: {
                            turning: function (e, page, view) {
                                
                            },
                            turned: function (e, page, view) {
                                var total = $(".flipbook").turn("pages");//总页数
                                
                                pageindex = Number(page);
                                if(playstate == 2){//圈选模式
                                    // alert("start_du_page:"+start_du_page +"end_du:"+end_du_page+"==="+index);
                                    if(start_du_page != pageindex){
                                         clearBorder();
                                        // $("#div_container div").css('border','0px solid white');
                                    }

                                    if(isfuduing){//正在读
                                        if(start_du_page == pageindex){
                                           clearBorder();
                                            // $("#div_container div").css('border','0px solid white');
                                            $(fudu_content[0]).css('border','1px solid #0099FF');
                                        }
                                        if(end_du_page == pageindex){
                                           clearBorder();
                                            // $("#div_container div").css('border','0px solid white');
                                            $(fudu_content[1]).css('border','1px solid red');
                                        }
                                    }else{
                                        //动态创建btn
                                        createCheckImage(pageindex);    
                                    }

                                    
                                    return;
                                }


                                //执行默认
                                dismissRead();
                                clearBorder();
                                // $("#div_container div").css('border','0px solid white');
                                //动态创建btn
                                createCheckImage(pageindex);

                            }
                        }
                    })
                }
                yepnope({
                    test: Modernizr.csstransforms,
                    yep: ['js/turn.js'],
                    complete: loadApp
                });
            }
            ;
        }
    }
}











//请求获取字典函数
function getDicts(){
    var params = {
            callbacktype:'apis/dicts'
        }

        //网络请求框架，需要传入成功函数回调和 失败函数回调
        net_request('get','apis/dicts',params,dictsCallBack,errorCallBack);
}


  //成功的回调函数
    function dictsCallBack(data){
        if(isNotNull(data)){
            console.log(data);
            if(isNotNull(data.data)&&data.data.length>0){
                var arrdata = data.data;
                for(var e=0;e<arrdata.length;e++){
                    if(isNotNull(arrdata[e].word) && isNotNull(arrdata[e].explain)){
                        var key = arrdata[e].word.toLowerCase();
                        var value = arrdata[e].explain;
                        dicdata[key] = value;
                    }
                }
            }
        }
    }

//  失败的回调函数
    function errorCallBack(data){
        console.log(data);
    }



//初始化swiper
/*function initPage(){


    //banner必备
    swiper = new Swiper('.swiper-container', {
       spaceBetween:30,
       followFinger:false,
       touchAngle:50,
       touchMoveStopPropagation:false,
       centeredSlides:true,
       touchRatio:1,
       speed:300,


       on: {
               // slideNextTransitionStart: function () {//下一页
               //   var index = swiper.activeIndex;
               //   console.log("slideNextTransitionStart"+index);
               //   // alert(index);
               // },
               // slidePrevTransitionStart:function (){// 上一页
               //   var index = swiper.activeIndex;
               //   console.log("slidePrevTransitionStart"+index);
               //   // alert(index);
               // },
              touchStart: function(swiper,even){
                console.log('bg____touchStart;');

                    // var endx, endy;
                    // endx = even.changedTouches[0].pageX;
                    // endy = even.changedTouches[0].pageY;
                    // var direction = getDirectionBegin(startx, starty, endx, endy);
                    // $(".swiper-container").css("zIndex",99);

                    var event = event || window.event;
                    starty = event.touches[0].pageY;
                },
                touchMove: function(swiper,even){
                // console.log('bg____touchMove;');

                var event = event || window.event;
                event.touches[0].pageY;

                var endx, endy;
                endx = event.changedTouches[0].pageX;
                endy = event.changedTouches[0].pageY;

                var direction = getDirectionBegin(startx, starty, endx, endy);
                // 
                
            },
            touchEnd: function (swiper,even){
                dismissVolume();
            },
             click: function(swiper,even){
                if(pageindex == 0){
                        var mySwiper = document.querySelector('.swiper-container').swiper;
                        mySwiper.slideTo(1,1000);                                        
                }
             },
               slideChangeTransitionStart:function(){//先执行start
                 
                 
             }
         }

     });
}*/


//改变播放音量
function changeVolume(num){
    $("#sound_set_div").show();
    console.log("改变："+num);
    // $("#sound_set_div_progress").height(cur_volume+"%");
    $("#sound_set_div_progress").height(Math.round(cur_volume)+"%");
    cur_volume = Number(cur_volume) - Number(num/70);
    console.log("改变音量："+Math.round(cur_volume));
    if(cur_volume > 100){
        cur_volume = 100;
    }
    if(cur_volume < 0){
        cur_volume = 0;
    }
    
    $("#sound_set_div_progress").height(Math.round(cur_volume)+"%");
    $("#v_progress").html("音量"+Math.round(cur_volume)+"%");
    audioHandler.audio.volume = Math.round(cur_volume)/100;
    

}

//关闭音量弹窗
function dismissVolume(){
    $("#sound_set_div").hide();;
    isshowvolume = false;    
}


function getNowFormatDate() {
    var date = new Date();
    var seperator1 = "";
    var seperator2 = "";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
    + "" + date.getHours() + seperator2 + date.getMinutes()
    + seperator2 + date.getSeconds();
    return currentdate;
}


var startx, starty;

    //获得角度
    function getAngle(angx, angy) {
        return Math.atan2(angy, angx) * 180 / Math.PI;
    };

    //根据起点终点返回方向 1向上 2向下 3向左 4向右 0未滑动
    function getDirection(startx, starty, endx, endy) {
        var angx = endx - startx;
        var angy = endy - starty;

        //如果滑动距离太短
        // if (Math.abs(angx) < 2 && Math.abs(angy) < 2) {
        //     return result;
        // }

        if(angx <= -5){//向左边滑动
            return 0;
        }else if(angx >5){//向右边滑动
            return 1;
        }else{
            return 2;
        }
    }


    //根据起点终点返回方向 1向上 2向下 3向左 4向右 0未滑动
    function getDirectionBegin(startx, starty, endx, endy) {
        var angx = endx - startx;
        var angy = endy - starty;
        //如果滑动距离太短
        // if (Math.abs(angx) < 2 && Math.abs(angy) < 2) {
        //     return result;
        // }
        console.log("endy:"+endy+"starty"+starty+"angy:"+angy);

        if(isshowvolume){
            if(angy >= 1){//向下滑动
                console.log("angy"+angy);
                changeVolume(angy);
            }else if(angy <= -1){//向上滑动
                changeVolume(angy);
            }else{

            }
        }

        if(angy >= 50){//开始调控音量
            isshowvolume = true;    
        }else if(angy < -50){
            isshowvolume = true;    
        }
        
    }


    function createCheckImage(pindex){
        console.log(pindex);
        if(position_data.length>0){
            for(var i = 0;i<position_data.length;i++){
                var pages = position_data[i].Rects;
                if(pindex == i){
                    if(pages.length>0){

                        var imgContainer=document.getElementById("div_container");
                    // $("#div_container").html("");
                    divs = new Array();
                    for (var j = 0; j<pages.length; j++){
                        var x = pages[j].X;
                        var y = pages[j].Y;
                        var w = pages[j].Width;
                        var h = pages[j].Height;
                        var duration = pages[j].SoundTime;
                        var duration_zh = pages[j].TSoundTime;
                        var translationtips = pages[j].Translate;
                        var curtext = pages[j].Content;
                        var cursound = pages[j].Sound;
                        var cursound_zh = pages[j].TSound;

                        var cid;
                        var div;
                        
                            imgContainer.style.height=100+"%";
                            div = document.createElement("div");
                            var aa = Number(i);
                            var bb = Number(j)+1;
                            cid = aa+"_"+bb;
                            div.id =cid;
                            div.setAttribute("cid",aa+"_"+bb);
                            div.setAttribute("curpage",aa+"");
                            div.setAttribute("currow",j+"");
                            div.setAttribute("pagenum",pages.length+"");

                            div.setAttribute("duration",Number(duration));
                            div.setAttribute("duration_zh",Number(duration_zh));
                            div.setAttribute("translationtips",translationtips);
                            div.setAttribute("curtext",curtext);
                            div.setAttribute("cursound",cursound);
                            div.setAttribute("cursound_zh",cursound_zh);

                            div.backgroundColor = "white";
                            div.style.width = (w*100)+"%";
                            div.style.height = (h*100)+"%";
                            if(isshowchecked){
                            div.style.border = "1px solid #bababa";
                            }else{
                            div.style.border = "0px solid #0099FF";    
                            }
                            
                            div.style.borderRadius = 5+'px';
                            // div.style.position="absolute";
                            div.style.zIndex = "100";
                            div.style.left=(x*100)+"%";
                            // div.style.zIndex = "100";
                            div.style.position = "absolute";
                            div.style.top=(y*100)+"%";
                            // div.style.backgroundColor="green";
                            // imgContainer.appendChild(div);
                            addDivChildByNotExist(imgContainer,div,cid);
                            






                                console.log($("#div_container").html());

                                div.addEventListener('touchstart',function(){
                                    var event = event || window.event;
                                    switch(event.type){
                                        case "touchstart":
                                        startx = event.touches[0].pageX;
                                        starty = event.touches[0].pageY;
                                        event.touches[0].pageY;
                                        break;

                                    }
                                    
                                }, false);
                                div.addEventListener('touchend',function(){
                                    var event = event || window.event;
                                    switch(event.type){
                                        case "touchstart":
                                                    // console.log("touchstart");
                                                    break;
                                                    case "touchend":
                                                     dismissVolume();
                                                    var endx, endy;
                                                    endx = event.changedTouches[0].pageX;
                                                    endy = event.changedTouches[0].pageY;
                                                    var direction = getDirection(startx, starty, endx, endy);
                                                    // alert(direction);
                                                    switch (direction) {

                                                        case 0://左边
                                                        toNextPage();
                                                        break;
                                                        case 1://右边
                                                        toPrevPage();
                                                        break;
                                                            case 2://不滑动
                                                            break;
                                                            default:
                                                        }
                                                        break;
                                                        case "touchmove":
                                                // event.preventDefault();//取消事件的默认动作
                                                console.log("touchmove");
                                                break;
                                            }

                                        }, false);



                                div.addEventListener('touchmove',function(){
                                    var event = event || window.event;
                                    switch(event.type){
                                            case "touchmove":
                                            var event = event || window.event;
                                            event.touches[0].pageY;

                                            var endx, endy;
                                            endx = event.changedTouches[0].pageX;
                                            endy = event.changedTouches[0].pageY;

                                            var direction = getDirectionBegin(startx, starty, endx, endy);

                                            break;
                                            }

                                        }, false);
                                // div.addEventListener("click", function (event){

                                //     alert("dd");
                                // },true);

                                imgContainer.onclick = function(event){
                                    if(pindex == 0){
                                        toPage(1);
                                    }
                                }

                                div.onclick=function(event){

                                    //判断如果不是本页面的创建的div，不能点击
                                    var this_div_pageindex = $(this).attr("curpage");
                                    // alert("this_div_pageindex----"+this_div_pageindex+"pageindex:"+pageindex);
                                    if(pageindex != this_div_pageindex){
                                        return;
                                    }

                                    nextpageindex_add = 1;//每次点击，叠加量归为1

                                    if(playstate == 4){//查词功能，点击弹出内容弹窗，选择复制查词
                                        searchWords(this);
                                        return;
                                    }

                                    if(playstate == 2){//圈选 复读模式
                                        if(fudu_content.length == 0){//还没有圈选
                                            start_du_page = Number(i);
                                            $(this).css('border','1px solid #0099FF');
                                            fudu_content[0] = this;
                                            $.toast("请再选择一个复读终点");
                                        }else{
                                            //开始复读
                                            fudu_content[1] = this;

                                            var a = ($(fudu_content[0]).attr("id")+"");
                                            var b = ($(fudu_content[1]).attr("id")+"");
                                            // alert(s_id_a+"="+s_id_b+"="+e_id_a+"="+e_id_b);
                                            //防止开始的地点大于结束的地点
                                            if(compareId(a,b) == 1){//a 比较大

                                                end_du_page = start_du_page;
                                                start_du_page = Number(i);
                                                fudu_content[1] = fudu_content[0];
                                                fudu_content[0] = this;

                                                $(fudu_content[0]).css('border','1px solid #0099FF');

                                            }else{
                                                end_du_page = Number(i);
                                            }

                                            $("#div_content_bg").show();//开始禁止模式 
                                            isfuduing = true;
                                            reread(fudu_content[0]);  
                                            // $(fudu_content[1]).css('border','1px solid red'); 
                                            toPage(Number($(fudu_content[0]).attr("curpage")));
                                        }
                                        
                                        return;
                                    }


                                    read(this);

                                };

                                //单独div对象添加到 集合中
                                if(divs.indexOf($("#"+cid)) == -1){
                                    divs[j] = $("#"+cid);
                                }
                                

                            }


                            if(page_divs.indexOf(divs) == -1){
                                page_divs[pindex] = divs;
                            }
                            

                            return;

                        }
                        

                    }

                }
            }


        }




//初始化audio
function initAudio(){

    var curalltime = 5;
    // audioHandler = $$("#music_player")[0];
    audioHandler = new AudioPlayer({
     id: 'music_player'
 });

    
    audioHandler.on('canplay', function (totalTime, name, item) {

        // console.log(audioHandler.audio.playbackRate);
        audioHandler.play();
        $("#bottom_menu_img2").attr("src","../img/icon_unplay.png");
        isreadingover = false;


        console.log('canplay');
        curalltime = totalTime;
    });



    audioHandler.on('ended' , function (){

            var record_curalltime = Math.ceil(curalltime*1.2);

            curtime = setTimeout(function(){
                isreadingover = true;
               if(playstate == 0){
                   $("#bottom_menu_img2").attr("src","../img/icon_play.png");
                   $("#div_tips").hide();

                   //判断是否需要跟读，处理跟读
                   commonFollow(record_curalltime,function(){
                        //跟读模式
                        $("#bottom_menu_img2").attr("src","../img/icon_play.png");
                        $("#div_tips").hide();
                    });

             }else if(playstate == 1){//全局阅读，本课

               if(Number(strs[1])>=Number(curpagenum) || ispause){
                audioHandler.pause();
                $("#bottom_menu_img2").attr("src","../img/icon_play.png");
                $("#div_tips").hide();

                //判断是否需要跟读，处理跟读
                commonFollow(record_curalltime,function(){
                        //跟读模式
                        audioHandler.pause();
                        $("#bottom_menu_img2").attr("src","../img/icon_play.png");
                        $("#div_tips").hide();
                    });
                }else{

                    var ccid = strs[0]+"_"+(Number(strs[1])+1);


                    //判断是否需要跟读，处理跟读
                    commonFollow(record_curalltime,function(){
                        //跟读模式
                        read($("#"+ccid));  
                    });
                    if(isfollow){
                        return;
                    }
                        //正常阅读
                        read($("#"+ccid));    
                }

             }else if(playstate == 2){//循环阅读，圈选复读
                // alert($(curobject).attr("cid")+"=="+$(fudu_content[1]).attr("cid")+"当前页词语数量:"+curpagenum);
                // strs = ($(curobject).attr("id")).split("_");

                if($(curobject).attr("cid") == $(fudu_content[1]).attr("cid")){//读完了,从头开始复读
                    // dismissFuDu();

                    isfuduing = true;
                    var fudu_pindex = $(fudu_content[0]).attr("curpage");
                    var fudu_pagenum = $(fudu_content[0]).attr("pagenum");


                    //判断是否需要跟读，处理跟读
                    commonFollow(record_curalltime,function(){

                        toPage((Number(fudu_pindex)));
                        //跟读模式
                        //跟读模式
                        reread(fudu_content[0]);  

                    });
                    
                    if(isfollow){//如果是录音模式，开始录制声音
                    //开始录制声音
                        return;
                    }

                    toPage((Number(fudu_pindex)));
                    reread(fudu_content[0]);  
                    // $(fudu_content[1]).css('border','1px solid red'); 
                }else{//没有读完，接着读

                    if(ispause){//暂停
                       dismissRead();
                       $("#div_content_bg").hide();
                       return;
                   }
                    var ccid = "";
                    if(Number(strs[1]) >= Number(curpagenum)){//本页面读取完了
                        ccid = (Number(strs[0])+1)+"_"+1;
                        // mySwiper.slideTo(Number($("#"+ccid).attr("curpage")),1000);           
                    }else{//本页面没有读完
                        ccid = strs[0]+"_"+(Number(strs[1])+1);
                    }


                    //判断是否需要跟读，处理跟读
                    commonFollow(record_curalltime,function(){
                        
                        if(Number(strs[1]) >= Number(curpagenum)){//本页面读取完了
                            toPage(Number($("#"+ccid).attr("curpage")));
                        }

                        //跟读模式
                        reread($("#"+ccid));   
                    });
                    
                    if(isfollow){//如果是录音模式，开始录制声音
                    //开始录制声音
                        return;
                    }



                    if(Number(strs[1]) >= Number(curpagenum)){//本页面读取完了
                        toPage(Number($("#"+ccid).attr("curpage")));
                    }
                    reread($("#"+ccid)); 
                }
                
             }else if(playstate == 3){//连续
                    if(ispause){//暂停
                       dismissRead();
                       return;
                   }
                   var ccid = ""
                // alert("str[1]:"+strs[1]+"--"+"curpagenum:"+curpagenum+"==");
                    if(Number(strs[1]) >= Number(curpagenum)){//本页面读取完了
                        ccid = (Number(strs[0])+1)+"_"+1;
                        // alert($("#"+ccid).attr("id"));
                        if(isNotNull($("#"+ccid).attr("curpage"))){

                            //判断是否需要跟读，处理跟读
                            commonFollow(record_curalltime,function(){
                                toPage(Number($("#"+ccid).attr("curpage")));
                                //跟读模式
                                read($("#"+ccid));    
                            });

                            if(isfollow){
                                return;
                            }
                            toPage(Number($("#"+ccid).attr("curpage")));
                            
                        }else{
                            var nextpageindex = Number(curpindex)+Number(nextpageindex_add);
                            // alert(nextpageindex);
                            createCheckImage(nextpageindex);
                            // alert($("#"+ccid).attr("id"));
                            if(isNotNull($("#"+ccid).attr("curpage"))){

                                //判断是否需要跟读，处理跟读
                                commonFollow(record_curalltime,function(){
                                    toPage(Number($("#"+ccid).attr("curpage")));
                                    nextpageindex_add = Number(nextpageindex_add) +1;
                                    //跟读模式
                                    read($("#"+ccid));    
                                });

                                if(isfollow){
                                    return;
                                }
                                toPage(Number($("#"+ccid).attr("curpage")));
                                nextpageindex_add = Number(nextpageindex_add) +1;
                            }else{//读完了全部
                                dismissRead();

                                //判断是否需要跟读，处理跟读
                                commonFollow(record_curalltime,function(){
                                    dismissRead();
                                });

                                return;
                            }
                        }
                        // alert("nextccid:"+Number($("#"+ccid).attr("curpage")));
                        // alert(ccid);
                    }else{//本页面没有读完
                        ccid = strs[0]+"_"+(Number(strs[1])+1);


                        //判断是否需要跟读，处理跟读
                        commonFollow(record_curalltime,function(){
                            //跟读模式
                            read($("#"+ccid));    
                        });
                    }
                    var curpagelength = $("#"+ccid).attr("pagenum");

                    
                    
                    if(isfollow){//如果是录音模式，开始录制声音
                    //开始录制声音
                        return;
                    }
                    read($("#"+ccid));    

             }else if(playstate == 4){//查词


             }else if(playstate == 5){//连续阅读单句
               if(ispause){

               }else{

                audioHandler.pause();
                //判断是否需要跟读，处理跟读
                commonFollow(record_curalltime,function(){
                    //跟读模式
                    //跟读模式
                    read(curobject);    
                });
                
                if(isfollow){//如果是录音模式，开始录制声音
                //开始录制声音
                    return;
                }
                    read(curobject);
                }
            }

        // },((curalltime*1200)/cur_play_sudu))
    },1000)

    });


    audioHandler.on('play' , function (){
        console.log('play');
        
        console.log(audioHandler.audio.playbackRate);
});

}




//公共的跟读
function commonFollow(ctime,nextcallback){

    if(isfollow){//如果是录音模式，开始录制声音
                        //开始录制声音
                            if(record_playnum == 1){//第一次
                                beginFollow(ctime);
                            }else if(record_playnum == 2){//第二次，开始播放本地录音
                                record_playnum = 1;
                                playRecord();

                                if(isNotNull(nextcallback)){
                                    setTimeout(function(){

                                        nextcallback();

                                    },(ctime+2));
                                }
                            }
        return true;
    }else{
        return false;
    }
}



//停止复读模式，重新开始阅读起点和终点
function click_fududiv_bg(){
    dismissRead();
    dismissFuDu();
    clearBorder();
    playstate == 2;
    createCheckImage(pageindex);
    $.toast("已停止复读，请重新选择阅读起点和终点");
    
}






//开始重复阅读
function reread(ob){

    //全局
    curpagenum = $(ob).attr("pagenum");
    curpindex = $(ob).attr("curpage");
    curobject = ob;

    // $("#div_container div").css('border','0px solid white');
    clearBorder();



    var recurpage = Number($(ob).attr("curpage"));
    if(end_du_page == recurpage){
        $(fudu_content[1]).css('border','1px solid red');
    }
    $(ob).css('border','1px solid #0099FF');
    var strid = $(ob).attr("id")+"";
    var tips = $(ob).attr("translationtips");
    var sound = $(ob).attr("cursound");
    var sound_zh = $(ob).attr("cursound_zh");
    var playdur = $(ob).attr("duration");

    console.log('id:'+strid);
    strs = strid.split("_");
    var msrc = rootpath+sound;
     $("#bottom_menu_img2").attr("src","../img/icon_unplay.png");
     $("#div_tips").hide();
     $("#div_tips").html(tips);
     if(istranslation){
        playdur = $(ob).attr("duration_zh");
        msrc = rootpath+sound_zh;
        $("#div_tips").show();   
    }
    if(isIOS()){
        msrc = msrc + "p3";
    }
    var list = [{
        name: strid,
        url: msrc,
        time: playdur
    }];

    //播放声音
    // $("#bgmusic").html("<source src="+msrc+">");
    // $("#bgmusic").get(0).load();

    ispause = 0;
    clearTimeout(curtime);
    audioHandler.clearList();
    audioHandler.add(list);
    audioHandler.loadIndex(0);

    if(cur_play_sudu > 1){//如果当前的速度大于1，ios 机型大于1 的速度回播放不出声音，用本地的播放器来代替播放
        var param = {
            type:'play_local_sounds',
            speed:cur_play_sudu,
            soundsrc:msrc
        };
        //开始去录音
        send_data(param);
    }
}


//开始阅读
function read(ob){

     //全局
    curpagenum = $(ob).attr("pagenum");
    curpindex = $(ob).attr("curpage");
    curobject = ob;

    // $("#div_container div").css('border','0px solid white');
    clearBorder();


    $(ob).css('border','1px solid #0099FF');
    var strid = $(ob).attr("id")+"";

    var tips = $(ob).attr("translationtips");
    var sound = $(ob).attr("cursound");
    var sound_zh = $(ob).attr("cursound_zh");
    var playdur = $(ob).attr("duration");

    console.log('id:'+strid);
    strs = strid.split("_");


    var msrc = rootpath+sound;
     $("#bottom_menu_img2").attr("src","../img/icon_unplay.png");
     $("#div_tips").hide();
     $("#div_tips").html(tips);
     if(istranslation){
        playdur = $(ob).attr("duration_zh");
        msrc = rootpath+sound_zh;
        $("#div_tips").show();   
    }
    if(isIOS()){
        msrc = msrc + "p3";
    }
    var list = [{
        name: strid,
        url: msrc,
        time: playdur
    }];

    //播放声音
    // $("#bgmusic").html("<source src="+msrc+">");
    // $("#bgmusic").get(0).load();

    ispause = 0;
    clearTimeout(curtime);
    audioHandler.clearList();
    audioHandler.add(list);
    audioHandler.loadIndex(0);

    if(cur_play_sudu > 1){//如果当前的速度大于1，ios 机型大于1 的速度回播放不出声音，用本地的播放器来代替播放
        var param = {
            type:'play_local_sounds',
            speed:cur_play_sudu,
            soundsrc:msrc
        };
        //开始去录音
        send_data(param);
    }

 }


//清空边框
function clearBorder(){
    if(!isshowchecked){
        $("#div_container div").css('border','0px solid white');
    }else{
        var divs = page_divs[pageindex];
        $("#div_container div").css('border','0px solid white');
        if(isNotNull(divs)){

            for(var i = 0;i<divs.length;i++){
                var cdiv = divs[i];
                console.log("当前页面的id："+cdiv.attr("id"));

                if(isNotNull(cdiv)){
                    if(i < Number(curpagenum) || curpagenum == 0){
                        $(cdiv).css('border','1px solid #bababa');
                    }
                    
                }
            }
        }
        
        // $("#div_container div").css('border','1px solid #bababa');
    }
}




//是否显示可点击读框
function showChecked(){
    if(!isshowchecked){
        $.toast("显示点读框");
        $("#img_showchecked").attr("src","../img/img_hand_check.png");
        isshowchecked = true;
        clearBorder();

    }else{
        $.toast("隐藏点读框");
        $("#img_showchecked").attr("src","../img/img_hand_uncheck.png");
        isshowchecked = false;
        clearBorder();
    }
}




//设置当前页面的z-index最大
function setCurZIndexTop(){
     
        for(var k = 0;k<page_divs.length;k++){
            var divs = page_divs[k];       
            if(isNotNull(divs)){
                for(var i = 0;i<divs.length;i++){
                    var cdiv = divs[i];
                    if(isNotNull(cdiv)){
                        if(k == pageindex){//当前页面z-index最大
                            console.log("当前页面的优先级最高："+k+"=====");
                            $(cdiv).attr("z-index",110);
                        }else{
                            $(cdiv).attr("z-index",100);
                        }
                        
                    }
                }
            }
        }
}






 function showmenu(){
    $("#div_words_bg").show();
    toshare();
}


//点击改变播放音频的状态
function readstate(){

    if(audioHandler.playing){//暂停
        ispause = 1;
        audioHandler.pause();
        $("#bottom_menu_img2").attr("src","../img/icon_play.png");
    }else{
        ispause = 0;
        
        if(isNotNull(audioHandler.list)){//如果为空，默认从头开始播放

            var curpro_play = audioHandler.audio.currentTime;
            console.log("当前的播放进度是："+audioHandler.audio.currentTime);
            if(isNotNull(curpro_play) && !isNaN(curpro_play)){
                curpro_play = curpro_play - 1;
                if(curpro_play < 0){
                    curpro_play = 0;
                }
                if(!isreadingover){
                    audioHandler.audio.currentTime = curpro_play;
                }
                
            }



            audioHandler.play();
        }else{

            var cdiv = page_divs[pageindex][0];
            
            read(cdiv,pageindex,position_data[pageindex].page_data.length);
            
            
        }
        
        $("#bottom_menu_img2").attr("src","../img/icon_unplay.png");
        
    }
}


//弹出层
function toshare(){
    $("#div_content_bg").hide();//关闭禁止模式 

    $(".am-share").addClass("am-modal-active"); 
    if($(".sharebg").length>0){
        $(".sharebg").addClass("sharebg-active");
    }else{
        $("body").append('<div class="sharebg"></div>');
        $(".sharebg").addClass("sharebg-active");
    }
    $(".sharebg-active,.share_btn").click(function(){
        $(".am-share").removeClass("am-modal-active");  
        setTimeout(function(){
            $(".sharebg-active").removeClass("sharebg-active"); 
            $(".sharebg").remove(); 
        },300);
    })

} 

function menu1(){
    $("#div_words_bg").hide();
    $("#li_menu4").css("background-image","url(../img/icon_menu1_off.png)");
    $("#li_menu5").css("background-image","url(../img/icon_menu2_off.png)");
    $("#li_menu6").css("background-image","url(../img/icon_menu3_off.png)");
    $("#li_menu7").css("background-image","url(../img/icon_menu4_off.png)");
    $("#li_menu8").css("background-image","url(../img/icon_menu5_off.png)");
    $("#li_menu9").css("background-image","url(../img/icon_menu6_off.png)");

    $("#li_menu4").css("background-image","url(../img/icon_menu1_on.png)");
    $(".am-share").removeClass("am-modal-active");  
    setTimeout(function(){
        $(".sharebg-active").removeClass("sharebg-active"); 
        $(".sharebg").remove(); 
    },300);
    playstate = 0;

    if(isfuduing){//判断是否正在复读
        dismissFuDu();
    }
    dismissRead();
}  

function menu2(){
    $("#div_words_bg").hide();
    $("#li_menu4").css("background-image","url(../img/icon_menu1_off.png)");
    $("#li_menu5").css("background-image","url(../img/icon_menu2_off.png)");
    $("#li_menu6").css("background-image","url(../img/icon_menu3_off.png)");
    $("#li_menu7").css("background-image","url(../img/icon_menu4_off.png)");
    $("#li_menu8").css("background-image","url(../img/icon_menu5_off.png)");
    $("#li_menu9").css("background-image","url(../img/icon_menu6_off.png)");

    $("#li_menu5").css("background-image","url(../img/icon_menu2_on.png)");
    $(".am-share").removeClass("am-modal-active");  
    setTimeout(function(){
        $(".sharebg-active").removeClass("sharebg-active"); 
        $(".sharebg").remove(); 
    },300);

    playstate = 1;

            if(isfuduing){//判断是否正在复读
                dismissFuDu();
            }
            dismissRead();
        } 

        function menu3(){
            $("#div_words_bg").hide();
            $("#li_menu4").css("background-image","url(../img/icon_menu1_off.png)");
            $("#li_menu5").css("background-image","url(../img/icon_menu2_off.png)");
            $("#li_menu6").css("background-image","url(../img/icon_menu3_off.png)");
            $("#li_menu7").css("background-image","url(../img/icon_menu4_off.png)");
            $("#li_menu8").css("background-image","url(../img/icon_menu5_off.png)");
            $("#li_menu9").css("background-image","url(../img/icon_menu6_off.png)");

            $("#li_menu6").css("background-image","url(../img/icon_menu3_on.png)");
            $(".am-share").removeClass("am-modal-active");  
            setTimeout(function(){
                $(".sharebg-active").removeClass("sharebg-active"); 
                $(".sharebg").remove(); 
            },300);

            // playstate = 5;
            playstate = 2;
            // $("#div_container div").css('border','0px solid white');
            clearBorder();

            fudu_content = new Array();

            if(isfuduing){//判断是否正在复读
                dismissFuDu();
            }
            dismissRead();
        } 


        function menu4(){
            $("#div_words_bg").hide();
            $("#li_menu4").css("background-image","url(../img/icon_menu1_off.png)");
            $("#li_menu5").css("background-image","url(../img/icon_menu2_off.png)");
            $("#li_menu6").css("background-image","url(../img/icon_menu3_off.png)");
            $("#li_menu7").css("background-image","url(../img/icon_menu4_off.png)");
            $("#li_menu8").css("background-image","url(../img/icon_menu5_off.png)");
            $("#li_menu9").css("background-image","url(../img/icon_menu6_off.png)");

            $("#li_menu7").css("background-image","url(../img/icon_menu4_on.png)");
            $(".am-share").removeClass("am-modal-active");  
            setTimeout(function(){
                $(".sharebg-active").removeClass("sharebg-active"); 
                $(".sharebg").remove(); 
            },300);

            playstate = 3;

            if(isfuduing){//判断是否正在复读
                dismissFuDu();
            }
            dismissRead();
        }

        function menu5(){
            $("#div_words_bg").hide();
            $("#li_menu4").css("background-image","url(../img/icon_menu1_off.png)");
            $("#li_menu5").css("background-image","url(../img/icon_menu2_off.png)");
            $("#li_menu6").css("background-image","url(../img/icon_menu3_off.png)");
            $("#li_menu7").css("background-image","url(../img/icon_menu4_off.png)");
            $("#li_menu8").css("background-image","url(../img/icon_menu5_off.png)");
            $("#li_menu9").css("background-image","url(../img/icon_menu6_off.png)");

            $("#li_menu8").css("background-image","url(../img/icon_menu5_on.png)");

            $(".am-share").removeClass("am-modal-active");  
            setTimeout(function(){
                $(".sharebg-active").removeClass("sharebg-active"); 
                $(".sharebg").remove(); 
            },300);

            playstate = 4;

            if(isfuduing){//判断是否正在复读
                dismissFuDu();
            }
            dismissRead();
        }


        function menu6(){
            $("#div_words_bg").hide();
    // $("#li_menu4").css("background-image","url(../img/icon_menu1_off.png)");
    // $("#li_menu5").css("background-image","url(../img/icon_menu2_off.png)");
    // $("#li_menu6").css("background-image","url(../img/icon_menu3_off.png)");
    // $("#li_menu7").css("background-image","url(../img/icon_menu4_off.png)");
    // $("#li_menu8").css("background-image","url(../img/icon_menu5_off.png)");
    // $("#li_menu9").css("background-image","url(../img/icon_menu6_off.png)");

    // $("#li_menu9").css("background-image","url(../img/icon_menu6_on.png)");

    $(".am-share").removeClass("am-modal-active");  
    setTimeout(function(){
        $(".sharebg-active").removeClass("sharebg-active"); 
        $(".sharebg").remove(); 
    },300);

            // playstate = 0;
            showChangeSudu();
            if(isfuduing){//判断是否正在复读
                dismissFuDu();
            }
            // dismissRead();
        }


//开始点击查词,弹出框框
function searchWords(ob){

    var str_tips_arr = $(ob).attr("title")+"";
    var text = $(ob).attr("curtext");
    curtrans = $(ob).attr("translationtips");
    $("#div_words_dialog_content").html(text);
    $("#div_words_dialog").show();
    $("#div_words_bg").show();
}

//关闭弹窗
function closeDialog(){
    $("#div_words_dialog").hide();
    $("#div_words_bg").hide();
}

//获取选中的文本，执行查词功能
function getCurText(){

    var text = window.getSelection().toString();
    //转换成小写
    text = text.toLowerCase();

    if((Object.keys(dicdata)).indexOf(text) == -1){
        //开始弹出查词的框
        // alert("查词解释：  暂无此解释");
//         $.alert('暂无此解释', '查词解释');
        native_showdialog("暂无此解释");
}else{
        //开始弹出查词的框
//        $.alert(" "+text+": "+dicdata[text], '查词解释');
        // alert("查词解释：  "+text+": "+dicdata[text]);
        native_showdialog(" "+text+": "+dicdata[text]);
    }
    
}

//停止阅读，比如切换菜单类型跟暂停时
function dismissRead(){
    //执行默认
    ispause = 1;
    audioHandler.pause();
    $("#bottom_menu_img2").attr("src","../img/icon_play.png");
    $("#div_tips").hide();
}

//停止复读
function dismissFuDu(){
    isfuduing = false;
    audioHandler.pause();
    $("#bottom_menu_img2").attr("src","../img/icon_play.png");
    $("#div_tips").hide();
    $("#div_content_bg").hide();
    // $("#div_container div").css('border','0px solid white');
    clearBorder();
    fudu_content = new Array();
}

//显示目录菜单
function showRightMenu(){

    $("#div_right").show();
    $("#div_words_bg").show();
    $("#div_words_dialog").hide();
    $(".am-share").removeClass("am-modal-active");  
    setTimeout(function(){
        $(".sharebg-active").removeClass("sharebg-active"); 
        $(".sharebg").remove(); 
    },300);
}

//关闭目录菜单
function dismissRightMenu(){

    $("#div_right").hide();
    $("#div_words_bg").hide();  

}


//弹出 速度设置层
function showChangeSudu(){
    $("#div_chang_sudu").show();
    $("#div_words_bg").show();
}

//隐藏速度层
function hideChangeSudu(){
    $("#div_chang_sudu").hide();
    // var audioElm = document.getElementById("music_player"); // Audio element
    var sudu = $$(".single-slider").val();   
    if(sudu == 6){//中
        audioHandler.audio.defaultPlaybackRate = 1;
        audioHandler.audio.playbackRate = 1;
        cur_play_sudu = 1;
    }else if(sudu > 6){//快
        var csd = (sudu - 6)*0.1;
        audioHandler.audio.defaultPlaybackRate = (1+csd);
        audioHandler.audio.playbackRate = (1+csd);
        cur_play_sudu = (1+csd);
    }else if(sudu < 6){//慢
        var csd = (6-sudu)*0.1;
        audioHandler.audio.defaultPlaybackRate = (1-csd);
        audioHandler.audio.playbackRate = (1-csd);
        cur_play_sudu = (1-csd);
    }
    console.log("当前的播放速度："+audioHandler.audio.playbackRate);
    // alert(audioElm.playbackRate);
}



//跟读，开启跟读模式
function follow(){

    if(isfollow){
        $.toast("已关闭跟读模式");
        $("#bottom_menu_img4").attr('src', '../img/img_icon_replay_off.png'); 
        isfollow = false;
    }else{
        $.toast("已开启跟读模式");
        $("#bottom_menu_img4").attr('src', '../img/img_icon_replay_on.png'); 
        isfollow = true;
        record_playnum = 1;
    }

}


//去播放跟读模式下，开始录音然后播放
function beginFollow(ptime){
    $.toast("开始录音");
    var param = {
        type:'begin_record',
        time:ptime
    };
    //开始去录音
    send_data(param);

}


//结束录音了，开始播放刚才的课本然后再次播放录音
function stopRecord(){
    //录音结束，再次播放上一次的声音，调用全局的一个播放
    if(ispause){          
    }else{
        record_playnum = 2;
        $.toast("开始播放");
        audioHandler.pause();
        read(curobject,curpindex,curpagenum);
    }
}

//结束课本文件后，开始去播放本地的录音，结束后，next
function playRecord(){

    var param = {
        type:'play_record'
    };
    //开始去录音
    send_data(param);
}



// http://dict-co.iciba.com/api/dictionary.php?w=go&key=DE5EB7C205E95AB2884CB14102E64369&type=json
//是否需要翻译提示
function translation_change(){
    if(istranslation){
        $.toast("已关闭翻译");
        $("#bottom_menu_img3").attr('src', '../img/img_translation_off.png'); 
        istranslation = false;
    }else{
        $.toast("已开启翻译");
        $("#bottom_menu_img3").attr('src', '../img/img_translation_on.png'); 
        istranslation = true;
    }
}


//添加子元素
function addDivChildByNotExist(fatherdiv,strchild,cid){

    if(isNotNull(fatherdiv)){
        if($("#"+cid).length > 0){
            console.log("remove")
            $("#"+cid).remove();
        }
        fatherdiv.appendChild(strchild);
    }
}

//比较id的大小，前者大返回 1 ，后者大返回-1，相同返回 0
function compareId(a,b){
    var s_id_a = (a.split("_"))[0];
    var s_id_b = (a.split("_"))[1];
    var e_id_a = (b.split("_"))[0];
    var e_id_b = (b.split("_"))[1];

    if(a == b){
        return 0;
    }

    if(Number(s_id_a) > Number(e_id_a)){
        return 1;
    }

    if((Number(s_id_a) == Number(e_id_a)) && 
        (Number(s_id_b) > Number(e_id_b)) ){
        return 1;
}

return -1;

}